package com.atguigu.msmservice.controller;
import cn.hutool.core.bean.BeanUtil;
import com.atguigu.commonutils.JwtUtil;
import com.atguigu.commonutils.Result;
import com.atguigu.commonutils.commonOrder.UCenterMemberOrder;
import com.atguigu.msmservice.entity.UcenterMember;
import com.atguigu.msmservice.entity.vo.RegisterVo;
import com.atguigu.msmservice.service.UCenterMemberService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author haoyue1573
 * @since 2023-03-21
 */
@RestController
@RequestMapping("/ucenterservice/apimember")
@CrossOrigin //跨域
@Slf4j
public class UcenterMemberController {

	@Resource
	private UCenterMemberService uCenterMemberService;

	@ApiOperation(value = "会员登录")
	@PostMapping("/login")
	public Result login(@RequestBody RegisterVo member) {
		Map<String, String> login = uCenterMemberService.login(member);
		String token = login.get("token");
		if (token!=null){
			return Result.ok().data("token",token).message("登录成功");
		}
		String message = login.get("message");
		return Result.error().message(message);
	}

	@ApiOperation(value = "会员注册")
	@PostMapping("/register")
	public Result register(@RequestBody RegisterVo registerVo){
		Result result = uCenterMemberService.register(registerVo);
		return result;
	}

	@PostMapping("/getMember")
	public Result getMember(HttpServletRequest request) throws Exception {
        //获取请求头中的用户id
		String token = request.getHeader("token");
		//解析token
		Claims claims = JwtUtil.parseJWT(token);
		String userId = claims.getSubject();
		if (userId==null){
			return Result.error();
		}
		LambdaQueryWrapper<UcenterMember> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(UcenterMember::getId,userId);
		UcenterMember memberServiceOne = uCenterMemberService.getOne(lambdaQueryWrapper);
		// TODO 返回的是键值对(注意键的名称)
		return Result.ok().data("user",memberServiceOne);
	}

	@PostMapping("/getMemberInformation/{userId}")
	public UCenterMemberOrder getMemberById(@PathVariable("userId") String userId){

		UcenterMember ucenterMember = uCenterMemberService.getById(userId);
        //将UCenterMember中的属性拷贝给UCenterMemberOrder
		UCenterMemberOrder uCenterMemberOrder = BeanUtil.copyProperties(ucenterMember, UCenterMemberOrder.class);
		return uCenterMemberOrder;
	}


	@GetMapping(value = "countregister/{day}")
	public Result registerCount(
			@PathVariable String day){
		Integer count = uCenterMemberService.countRegisterByDay(day);
		return Result.ok().data("countRegister", count);
	}

}

